package com.jingdianjichi.wx.handler;

import com.jingdianjichi.wx.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ReceiveMsgHander implements WxMsgHandler {
    public static final String KEY_WORD = "验证码";

    private static final String LOGIN_PREFIX = "loginCode";

    @Resource
    private RedisUtil redisUtil;

    @Override
    public WxMsgTypeEnum getMsgType() {
        return WxMsgTypeEnum.TEXT_MSG;
    }

    @Override
    public String dealMsg(Map<String, String> msgMap) {
        log.info("接收到用户文本消息");
        String content = msgMap.get("Content");
        if (content.equals("qjj")) {
            return "/:heart";
        } else if (content.equals(KEY_WORD)) {
            Random random = new Random();
            int verifyCode = random.nextInt(10000);
            String captcha = String.format("%04d", verifyCode);
            String key = redisUtil.buildKey(LOGIN_PREFIX, captcha);
            redisUtil.setNx(key, msgMap.get("FromUserName"), 5L, TimeUnit.MINUTES);
            return "您的验证码是" + captcha + ",五分钟内有效";
        }
        return "不对";
    }
}
